const db = require('../config/DBconnector');
const { DataTypes } = require('sequelize');
const { numberGetter } = require('../utils/ModelUtil');
const BusinessError = require('../exception/businessError');
const { CashAction } = require('../constants/DbEnum');

const name = 'CashRecord';

const fields = {
  username: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  action: {
    type: DataTypes.STRING(12),
    allowNull: false,
  },
  amount: {
    type: DataTypes.DECIMAL(20, 4),
    allowNull: false,
    validate: { min: 0.0001 },
    get: numberGetter(),
  },
  beforeBalance: {
    type: DataTypes.DECIMAL(20, 4),
    allowNull: false,
    validate: { min: 0.0001 },
    get: numberGetter(),
  },
  afterBalance: {
    type: DataTypes.DECIMAL(20, 4),
    allowNull: false,
    validate: { min: 0.0001 },
    get: numberGetter(),
  },
  paymentInfo: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  status: {
    type: DataTypes.STRING(12),
    allowNull: false,
  },
};

const validate = {
  validateBalance() {
    let valid = false;
    if (
      this.action == CashAction.DEPOSIT &&
      this.beforeBalance + this.amount == this.afterBalance
    ) {
      valid = true;
    } else if (
      this.action == CashAction.WITHDRAW &&
      this.beforeBalance - this.amount == this.afterBalance
    ) {
      valid = true;
    }

    if (!valid) {
      throw new BusinessError(400, 'Invalid record');
    }
  },
};

const model = db.define(name, fields, { validate });

module.exports = model;
